<template>
  <div class="book-list">
    <div class="header">
      <h2>图书列表</h2>
      <div style="display: flex; gap: 10px; align-items: center;">
        <el-button type="success" @click="batchDialogVisible = true" :icon="Plus">批量添加图书</el-button>
        <el-button type="primary" @click="handleAdd" :icon="Plus">添加图书</el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入书名、作者、ISBN或出版社"
        style="width: 300px"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch" :icon="Search">搜索</el-button>
        </template>
      </el-input>
    </div>

    <!-- 图书列表 -->
    <el-table
      :data="bookList"
      v-loading="loading"
      style="width: 100%"
      border
    >
      <el-table-column prop="isbn" label="ISBN" width="150" />
      <el-table-column prop="title" label="书名" min-width="200" />
      <el-table-column prop="author" label="作者" width="120" />
      <el-table-column prop="publisher" label="出版社" width="150" />
      <el-table-column prop="category" label="分类" width="100" />
      <el-table-column prop="totalCopies" label="总册数" width="80" align="center" />
      <el-table-column prop="availableCopies" label="可借册数" width="100" align="center" />
      <el-table-column prop="location" label="存放位置" width="120" />
      <el-table-column label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(row)"
          >删除</el-button>
          <el-button 
            size="small" 
            :type="row.status === 1 ? 'warning' : 'success'"
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 1 ? '下架' : '上架' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[5, 10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑图书对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="ISBN" prop="isbn">
          <el-input v-model="form.isbn" placeholder="请输入ISBN号" />
        </el-form-item>
        <el-form-item label="书名" prop="title">
          <el-input v-model="form.title" placeholder="请输入书名" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="form.publisher" placeholder="请输入出版社" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="计算机" value="计算机" />
            <el-option label="文学" value="文学" />
            <el-option label="历史" value="历史" />
            <el-option label="科学" value="科学" />
            <el-option label="艺术" value="艺术" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="总册数" prop="totalCopies">
          <el-input-number v-model="form.totalCopies" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="存放位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入存放位置" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入图书描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量添加图书对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量添加图书" width="1000px" class="batch-dialog">
      <div style="max-height: 400px; overflow-y: auto; overflow-x: auto; min-width: 950px;">
        <el-table :data="batchBooks" style="width: 100%; min-width: 950px;" border :header-cell-style="{background:'#fafafa'}">
          <el-table-column label="ISBN" :min-width="120">
            <template #header>
              <span style="color: red">*</span>ISBN
            </template>
            <template #default="{ row }">
              <el-input v-model="row.isbn" placeholder="请输入ISBN号" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="书名" :min-width="140">
            <template #header>
              <span style="color: red">*</span>书名
            </template>
            <template #default="{ row }">
              <el-input v-model="row.title" placeholder="请输入书名" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="作者" :min-width="100">
            <template #header>
              <span style="color: red">*</span>作者
            </template>
            <template #default="{ row }">
              <el-input v-model="row.author" placeholder="请输入作者" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="出版社" :min-width="100">
            <template #default="{ row }">
              <el-input v-model="row.publisher" placeholder="请输入出版社" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="分类" :min-width="100">
            <template #header>
              <span style="color: red">*</span>分类
            </template>
            <template #default="{ row }">
              <el-select v-model="row.category" placeholder="请选择分类" size="small" style="width: 100%">
                <el-option label="计算机" value="计算机" />
                <el-option label="文学" value="文学" />
                <el-option label="历史" value="历史" />
                <el-option label="科学" value="科学" />
                <el-option label="艺术" value="艺术" />
                <el-option label="其他" value="其他" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="总册数" :min-width="150">
            <template #header>
              <span style="color: red">*</span>总册数
            </template>
            <template #default="{ row }">
              <el-input-number v-model="row.totalCopies" :min="1" size="small" style="width: 100%;" />
            </template>
          </el-table-column>
          <el-table-column label="存放位置" :min-width="100">
            <template #default="{ row }">
              <el-input v-model="row.location" placeholder="请输入存放位置" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="状态" :min-width="80">
            <template #default="{ row }">
              <el-radio-group v-model="row.status" size="small">
                <el-radio :label="1">上架</el-radio>
                <el-radio :label="0">下架</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="__action" width="90" :show-overflow-tooltip="false" :formatter="() => ''" :resizable="false">
            <template #default="{ $index }">
              <div style="white-space: nowrap;">
                <el-button size="small" type="danger" @click="removeBatchRow($index)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin: 10px 0; text-align: left;">
        <el-button type="primary" @click="addBatchRow" size="small">添加一行</el-button>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchBooks" :loading="batchSubmitLoading">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { getBookList, addBook, updateBook, deleteBook, updateBookStatus, batchAddBooks } from '@/api/book'

// 响应式数据
const loading = ref(false)
const bookList = ref([])
const searchKeyword = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const formRef = ref()
const batchDialogVisible = ref(false)
const batchBooks = ref([
  { isbn: '', title: '', author: '', publisher: '', category: '', totalCopies: 1, location: '', status: 1 }
])
const batchSubmitLoading = ref(false)

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const form = reactive({
  id: null,
  isbn: '',
  title: '',
  author: '',
  publisher: '',
  category: '',
  description: '',
  totalCopies: 1,
  location: '',
  status: 1
})

// 表单验证规则
const rules = {
  isbn: [
    { required: true, message: '请输入ISBN号', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入书名', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  totalCopies: [
    { required: true, message: '请输入总册数', trigger: 'blur' }
  ]
}

// 获取图书列表
const fetchBookList = async () => {
  loading.value = true
  try {
    const response = await getBookList({
      page: pagination.current,
      size: pagination.size,
      keyword: searchKeyword.value
    })
    if (response.code === 200) {
      bookList.value = response.data.records
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取图书列表失败')
    }
  } catch (error) {
    console.error('获取图书列表失败:', error)
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchBookList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  fetchBookList()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  fetchBookList()
}

// 添加图书
const handleAdd = () => {
  dialogTitle.value = '添加图书'
  dialogVisible.value = true
  resetForm()
}

// 编辑图书
const handleEdit = (row) => {
  dialogTitle.value = '编辑图书'
  dialogVisible.value = true
  Object.assign(form, row)
}

// 删除图书
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这本图书吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteBook(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchBookList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除图书失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const response = await updateBookStatus(row.id, newStatus)
    if (response.code === 200) {
      ElMessage.success('状态更新成功')
      fetchBookList()
    } else {
      ElMessage.error(response.message || '状态更新失败')
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('状态更新失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const response = form.id 
      ? await updateBook(form)
      : await addBook(form)
    
    if (response.code === 200) {
      ElMessage.success(form.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      fetchBookList()
    } else {
      ElMessage.error(response.message || (form.id ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    isbn: '',
    title: '',
    author: '',
    publisher: '',
    category: '',
    description: '',
    totalCopies: 1,
    location: '',
    status: 1
  })
}

function addBatchRow() {
  batchBooks.value.push({ isbn: '', title: '', author: '', publisher: '', category: '', totalCopies: 1, location: '', status: 1 })
}

function removeBatchRow(index) {
  batchBooks.value.splice(index, 1)
}

async function submitBatchBooks() {
  if (batchBooks.value.length === 0) {
    ElMessage.warning('请至少添加一本图书')
    return
  }
  batchSubmitLoading.value = true
  try {
    const response = await batchAddBooks(batchBooks.value)
    if (response.code === 200) {
      ElMessage.success('批量添加成功')
      batchDialogVisible.value = false
      batchBooks.value = [
        { isbn: '', title: '', author: '', publisher: '', category: '', totalCopies: 1, location: '', status: 1 }
      ]
      fetchBookList()
    } else {
      ElMessage.error(response.message || '批量添加失败')
    }
  } catch (error) {
    console.error('批量添加失败:', error)
    ElMessage.error('批量添加失败')
  } finally {
    batchSubmitLoading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchBookList()
})
</script>

<style scoped>
.book-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0 20px;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-bar {
  padding: 0 20px;
  margin-bottom: 20px;
}

.el-table {
  flex: 1;
  margin: 0 20px;
}

.pagination {
  padding: 20px;
  display: flex;
  justify-content: center;
  background-color: #fff;
  border-top: 1px solid #ebeef5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.batch-dialog .el-dialog__body {
  padding: 20px 10px 10px 10px;
}
</style> 